﻿using Microsoft.Media.IngestClient;
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;

namespace Microsoft.Media.CaptureClient
{
    internal class StreamOutputConsumer : IPushOutputConsumer
    {
        public uint BufferSize { get; set; }

        Stream outputStream;
        bool closeOnTerminate;

        public StreamOutputConsumer(Stream outputStream, bool closeOnTerminate)
        {
            BufferSize = 1024;
            this.outputStream = outputStream;
            this.closeOnTerminate = closeOnTerminate;
        }

        public async Task SendDataAsync(Stream inputStream, CancellationToken c, IProgress<ulong> progress)
        {
            ulong bytesRead = 0;
            do
            {
                byte[] buffer = new byte[60 * 1024];
                var read = await inputStream.ReadAsync(buffer, 0, buffer.Length, c);
                if (read == 0) break;

                await outputStream.WriteAsync(buffer, 0, read, c);
                await outputStream.FlushAsync(c);

                bytesRead += (ulong)read;
                progress.Report(bytesRead);
            } while (true);
        }

        public async Task TerminateAsync()
        {
            await outputStream.FlushAsync();
            if (closeOnTerminate) outputStream.Dispose();
        }
    }
}
